﻿/********************************************************************************/
// <copyright file="EventController.cs" company="Asia E-Business Solutions">
//     Copyright © 2012. All right reserved
// </copyright>
// <history>
//     <change who="Phuoc Le" date="02/01/2013 4:23:34 PM">Created</change>
// </history>
/********************************************************************************/


using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using JLL.China.Application;
using JLL.China.Infrastructure.Services;
using JLL.China.Web.Areas.Portal.Models;
using JLL.China.Model;
using JLL.China.Model.DTO;
using JLL.China.Web.Libraries;

namespace JLL.China.Web.Areas.Portal.Controllers
{
    

    public class EventController : Controller
    {
        protected int defaultPageSize = Int32.Parse(WebConfigurationManager.AppSettings["page_size_default"]);


        public EventController()
        {
            ViewData["now_controller"] = "Portal/Event/";
            ViewData["TitleEvent"] = "Update/Insert Event";
            
        }


        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ChangeNumOfRow(FormCollection f)
        {
            Session["page_size_default"] = f["display_show_page"].ToString();
            Session["message"] = "Changed number of row";
            return RedirectToAction("Index");
        }
        public bool checkUserLogin()
        {
            var loginAcc = this.Session[Constants.Session_User] as Model.Admin;
            if (loginAcc == null)
            {
                return false;
            }
            return true;
        }
        //
        // GET: /Portal/Event/
        [Authorize]
        public ActionResult Index(int? page, EventSearchOrder? orderby, bool? descending)
        {
            ViewData["TitleEvent"] = "Event";
            var model = new EventsModel();
            var searchCriteria = new EventSearchCriteria { };

            if (orderby.HasValue)
            {
                searchCriteria.OrderBy = orderby.Value;
            }

            if (descending.HasValue)
            {
                searchCriteria.Descending = descending.Value;
            }

            model.Events = EventService.Search(searchCriteria);
            string url = VirtualPathUtility.ToAbsolute("~/Portal/Event");

            if (orderby.HasValue)
            {
                url = url + string.Format("&orderby={0}", orderby.Value);
            }
            if (descending == true)
            {
                url = url + string.Format("&descending={0}", descending.Value);
            }
            if (Session["page_size_default"] != null)
            {
                ViewData["per-page"] = Session["page_size_default"].ToString();
                defaultPageSize = Int32.Parse(Session["page_size_default"].ToString());
            }
            else
            {
                ViewData["per-page"] = defaultPageSize;
            }
            int currentPageIndex = page.HasValue ? page.Value : 1;
            //Strore Session
            Session["pageindex"] = currentPageIndex;
            
            var eventModel = new JLL.China.Web.Areas.Portal.Models.EventsModel();

            
            model.OrderBy = searchCriteria.OrderBy;
            model.IsDescending = searchCriteria.Descending;
            model.RequestURL = this.Request.Url.ToString();
            var models = EventService.Search(searchCriteria).ToPagedList(currentPageIndex, defaultPageSize);
            //model =JLL.China.Web.Areas.Portal.Models.EventsModel.ToPagedList(currentPageIndex, defaultPageSize);
          /*  ViewData["eventcount"] = models.Count;
            Session["eventcount"] = models.Count;*/
            //model.Events = EventService.GetAllEvents();
            return View(models);
        }

        //
        // GET: /Portal/Event/Edit/5

        public ActionResult Edit(int id)
        {
            var model = new EventModel();
            model.Event = EventService.GetEvent(id);

            return View("Create", model);
        }

        public ActionResult DeleteFile(decimal? e, decimal? l,string filename)
        {
            System.IO.File.Delete(filename);
//            Session["message"] = "Delete file successfully.";
//            Session["messageType"] = "Success";
            ShowMessage("Delete file successfully.", "Success");
            return RedirectToAction("Create", new {eventId = e});
        }

        //
        // GET: /Portal/Event/Create/2?language=1
        [Authorize]
        public ActionResult Create(decimal? eventId)
        {
            if (!checkUserLogin())
            {
                return RedirectToAction("LogIn", "Home", new { area = "" });
            }
            ViewData["TitleEvent"] = "Update/Insert Event";
//            ViewData["eventcount"] = Session["eventcount"];
            /*when update */
            if (eventId != null)
            {
                var e = EventService.FindByIDandLanguageFID(eventId, 1);
                if (e != null)
                {
                    //get all file from folder
                    var eLocal = EventService.FindByIDandLanguageFID(eventId, 2);
                    List<FileInfo> files = FromFolder(e.Event_ID.ToString());
                    ViewData["files"] = files;
                    var eventmodel = new EventModel();
                    eventmodel.Event = e;
                    eventmodel.Event_Local = eLocal;
                    return View(eventmodel);
                }
                return RedirectToAction("Index");

            }
            /*when insert*/
            var model = new EventModel();
            model.Event = new Event();
            //model.Event.EventDate = Nullable<DateTime>;
            return View(model);
        }

        

        List<FileInfo> FromFolder(string folderName)
        {
            string path = Server.MapPath("~/Media/Event/" + folderName);
            //string SourecPath = HttpContext.Request.MapPath(path);
            if (!Directory.Exists(path))
            {
                return null;
            }
            DirectoryInfo sourcedinfo = new DirectoryInfo(path);

            var files = sourcedinfo.GetFiles();
           List<FileInfo> fs = new List<FileInfo>();
            foreach (var fileInfo in files)
            {
//                if (fileInfo.Name.StartsWith(sufix))
//                {
                    fs.Add(fileInfo);
//                }
                  
            }
            return fs;
        }


        /// <summary>
        /// save file to folder has an name(id)
        /// </summary>
        /// <param name="files"></param>
        /// <param name="folderId"></param>
        /// <returns></returns>
        private bool UploadFilesToEventMedia(IEnumerable<HttpPostedFileBase> files, decimal? folderId)
        {
            try
            {
                if (files == null)
                {
                    return true;
                }

                string mediaRootPath = Server.MapPath("~/Media/Event/");
                string storagePath;
                if (folderId != null)
                    storagePath = mediaRootPath + folderId.ToString();
                else storagePath = mediaRootPath + "0";
                string name, fullFilePath;
                foreach (var file in files)
                {
                    if (file == null)
                    {
                        continue;
                    }

                    if (!Directory.Exists(storagePath))
                    {
                        Directory.CreateDirectory(storagePath);
                    }
                    name = System.IO.Path.GetFileName(file.FileName);
                    fullFilePath = storagePath + "\\"  + name;
                    file.SaveAs(fullFilePath);

                }
            }
            catch (Exception)
            {

                return false;
            }
            return true;
        }
/*
        private string FormatFileName(string fullpath, string filename)
        {
            string file_ext = Path.GetExtension(fullpath);
            if (!System.IO.File.Exists(fullpath))
            {
                return filename + file_ext;
            }
            string new_file_name = "";
            string path = Path.GetDirectoryName(fullpath);
            for (int i = 1; i < 10; i++)
            {
                if (!System.IO.File.Exists(path + "\\" + filename + "_" + i + file_ext))
                {
                    new_file_name = filename + "_" + i + file_ext;
                    return new_file_name;
                }
            }
            return new_file_name;
        }
 */
        //
        // POST: /Portal/Event/Create

        void ShowMessage(string msg,string type)
        {
            Session["message"] = msg;
            Session["messageType"] = type;
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(EventModel model, IEnumerable<HttpPostedFileBase> files)
        {
            if (!checkUserLogin())
            {
                return RedirectToAction("LogIn", "Home", new { area = "" });
            }
            model.Event.EventType = "launch";

            decimal? folderID = 0;
            var loginAcc = this.Session[Constants.Session_User] as Model.Admin;
            if (loginAcc != null)
            {
                model.Event.Admin = loginAcc;
                model.Event.CreatedBy = loginAcc.UserName;
                model.Event.DateCreated = DateTime.Now;
            }
            else
            {
                return RedirectToAction("Login", "Home", new { area = "" });
            }
            
            if (model.Event.Event_ID > 0)//update
            {
                try
                {
                    EventService.UpdateEvent(model.Event, model.Event_Local);
                    folderID = model.Event.Event_ID;
                    EventService.CommitChanges();
                    string language = string.Empty;
                    bool flag = UploadFilesToEventMedia(files, folderID);
//                    Session["message"] = "Records updated successfully.";
//                    Session["messageType"] = "Success";
                    ShowMessage("Records updated successfully.", "Success");
                }
                catch (Exception)
                {
//                    Session["message"] = "Records updated unsuccessfully.";
//                    Session["messageType"] = "Error";
                    ShowMessage("Records updated unsuccessfully.", "Error");
                    return RedirectToAction("Index");
                }
            }
            else /*insert*/
            {
                try
                {
                    folderID = EventService.CreateNewEvent(model.Event,model.Event_Local);
                    EventService.CommitChanges();
                    bool flag = UploadFilesToEventMedia(files, folderID);
//                    Session["message"] = "Records updated successfully.";
//                    Session["messageType"] = "Success";
                    ShowMessage("Records updated successfully.", "Success");
                    //return RedirectToAction("Create", new { eventId = folderID });
                }
                catch (Exception)
                {
//                    Session["message"] = "Records updated unsuccessfully.";
//                    Session["messageType"] = "Error";
                    ShowMessage("Records updated unsuccessfully.", "Error");
                    //return RedirectToAction("Index");
                }
            }

            //return Content("<script>alert('" + model.Event.ID + "')</script>");



            return RedirectToAction("Index");
        }

        //
        // GET: /Portal/Event/Delete/5
        public ActionResult Delete(decimal id)
        {
            if (!checkUserLogin())
            {
                return RedirectToAction("LogIn", "Home", new { area = "" });
            }
           // var model = new Event { ID = id };
            if (id != 0)
            {
                EventService.DeleteEvent(id);
                EventService.CommitChanges();
                ShowMessage("Records updated successfully.", "Success");
            }
         
            return RedirectToAction("Index");
        }

        //
        // GET: /Portal/Event/ChangeStatus/5
        public ActionResult ChangeStatus(int id, bool status, EventSearchOrder? orderby, bool? descending)
        {
            //var model = EventService.GetEvent(id);

            //model.Status = model.Status ? false : true;

            //EventService.UpdateEvent(model);
            //EventService.CommitChanges();
            if (!checkUserLogin())
            {
                return RedirectToAction("LogIn", "Home", new { area = "" });
            }
            EventService.ChangeEventStatus(id.ToString(), !status);
            ShowMessage("Records updated successfully.", "Success");
            // return RedirectToAction("Index", new { orderby = orderby.Value, descending = descending.Value });Session["pageindex"]
            return RedirectToAction("Index", new { page = Session["pageindex"] });
        }

        ///GET: /Portal/Event/SelectedEvent?status=active
        public ActionResult SelectedEvent(string status, IEnumerable<decimal> selected)
        {
            try
            {
                if (!checkUserLogin())
                {
                    return RedirectToAction("LogIn", "Home", new { area = "" });
                }
                string arr_id = "0";
                foreach (var key in selected)
                {
                    arr_id += "," + key.ToString();
                }
                if (status.Equals("active"))
                {
                    EventService.ChangeEventStatus(arr_id, true);
                }

                if (status.Equals("inactive"))
                {
                    EventService.ChangeEventStatus(arr_id, false);
                }

                if (status.Equals("remove"))
                {
                    EventService.RemoveSelected(arr_id);
                }
//                Session["message"] = "Records updated successfully.";
//                Session["messageType"] = "Success";
                ShowMessage("Records updated successfully.", "Success");
            }
            catch (Exception ex)
            {
//                Session["message"] = "Records updated unsuccessfully.";
//                Session["messageType"] = "Error";
                ShowMessage("Records updated unsuccessfully.", "Error");
            }
           
            
            return RedirectToAction("Index/1?page=" + Session["pageindex"].ToString());
          //  return RedirectToAction("Index");
        }
    }
}
